import { getProductList } from "@/api/product";
import { InfiniteScroll, List } from "antd-mobile";
import { FC, useEffect, useState } from "react";

type Props = {
  classId: string;
  brandId: string;
};

const ProductList: FC<Props> = ({ classId, brandId }) => {
  const [query, setQuery] = useState({
    pageIndex: 1, // 页码
    pageSize: 20, // 每页显示条数
  });

  const [list, setList] = useState<API.Product[]>([]);
  const [hasMore, setHasMore] = useState(true);

  // 加载更多
  const loadMore = async () => {
    const resp = await getProductList(
      classId,
      brandId,
      query.pageIndex,
      query.pageSize
    );

    // 追加 list
    setList((list) => [...list, ...resp.productList]);

    // 是否还有更多
    setHasMore(+resp.pageInfo.pageIndex < resp.pageInfo.totalPage);

    // 自增 pageIndex
    setQuery((query) => ({ ...query, pageIndex: query.pageIndex + 1 }));
  };

  // 监听 classId, brandId 从新获取数据
  useEffect(() => {
    // 重置 list
    setList([]);
    // 重置 hasMore
    setHasMore(true);
    // 重置 pageIndex
    setQuery((query) => ({ ...query, pageIndex: 1 }));
  }, [classId, brandId]);

  return (
    <div style={{ flex: 1, overflowY: "auto" }}>
      <List>
        {list.map((item) => (
          <List.Item key={item.productId} arrow extra={item.productMaxPrice}>
            {item.productName}
          </List.Item>
        ))}
      </List>

      <InfiniteScroll threshold={50} hasMore={hasMore} loadMore={loadMore} />
    </div>
  );
};

export default ProductList;
